from flask import Blueprint,jsonify
from flask_restful import Api,Resource,marshal,fields,reqparse
from common.models.course import *
from sqlalchemy import and_
import json
from common.utils.login_auth import login_auth

course_bp = Blueprint('course_bp',__name__,url_prefix='/course')
api = Api(course_bp)

tag_fields = {
    'id':fields.Integer,
    'title':fields.String,
    'sequence':fields.Integer,
}
course_fields = {
    'id':fields.Integer,
    'title':fields.String,
    'desc':fields.String,
    'img_path':fields.String,
    'course_type':fields.Integer,
    'status':fields.Integer,
    'follower':fields.Integer,
    'learner':fields.Integer,
    'create_time':fields.DateTime
}

chapters_fields = {
    'id':fields.Integer,
    'title':fields.String,
    'serial_num':fields.Integer
}

sections_fields = {
    'id':fields.Integer,
    'title':fields.String,
    'serial_num':fields.Integer,
    'learn_time':fields.DateTime,
    'content':fields.String,
    'video':fields.String,
    'seq_num':fields.Integer,
    'like_count':fields.Integer
}

class TagsResource(Resource):
    def get(self):
        try:
            tags = Tag.query.all()
            return jsonify(code=200,msg='标签获取成功',data=marshal(tags,tag_fields))
        except Exception as e:
            return jsonify(code=400,msg='标签获取失败')

class CourseAll(Resource):
    def get(self):
        '''获取所有课程'''
        parser = reqparse.RequestParser()
        params = ['page','size','tag_id','free','online','sort']
        for data in params:
            parser.add_argument(data)
        args = parser.parse_args()
        tag_id = args['tag_id']
        free = args['free']
        online = args['online']
        sort = args['sort']
        # 获取全部
        if tag_id == '' and free == '' and online == '' and sort == '':
            courses = Course.query.all()
            return jsonify(code=200, msg='课程获取成功', data=marshal(courses, course_fields))

        # 点击分类
        if free and tag_id == '' and online == '' and sort == '':
            free = CourseType.query.filter_by(title=free).first()
            course = free.course
            data = marshal(course,course_fields)
            return jsonify(code=200, msg='课程获取成功', data=data)

        # 点击标签
        if tag_id and free == '' and online == '' and sort == '':
            tag = Tag.query.filter_by(id=tag_id).first()
            course = tag.course
            data = marshal(course, course_fields)
            return jsonify(code=200, msg='课程获取成功', data=data)

        # 点击状态
        if online and free == '' and tag_id == '' and sort == '':

            course = Course.query.filter_by(status=online).all()
            print(course)
            data = marshal(course, course_fields)
            return jsonify(code=200, msg='课程获取成功', data=data)

        # 点击排序
        if tag_id == '' and free == '' and online == '' and sort:
            if sort == '1':
                course = Course.query.order_by(Course.create_time.desc()).all()
                data = marshal(course, course_fields)
                return jsonify(code=200, msg='课程获取成功', data=data)
            else:
                course = Course.query.order_by(Course.follower.desc()).all()
                data = marshal(course, course_fields)
                return jsonify(code=200, msg='课程获取成功', data=data)

        # 点击分类 和 标签
        if tag_id  and free and online == '' and sort == '':
            free = CourseType.query.filter_by(title=free).first()
            course1 = free.course
            tag = Tag.query.filter_by(id=tag_id).first()
            course2 = tag.course
            data1 = marshal(course1,course_fields)
            data2 = marshal(course2,course_fields)
            data=[]
            for i in data1:
                if i in data2:
                    data.append(i)
            return jsonify(code=200, msg='课程获取成功', data=data)

        # 点击分类 和 状态
        if tag_id == '' and free and online and sort == '':
            free = CourseType.query.filter_by(title=free).first()
            course = Course.query.filter(and_(Course.course_type==free.id,Course.status==online)).all()
            data = marshal(course, course_fields)


            return jsonify(code=200, msg='课程获取成功', data=data)


        # 点击分类 和排序
        if tag_id == '' and free and online == '' and sort:

            free = CourseType.query.filter_by(title=free).first()
            course = Course.query.filter_by(course_type=free.id).order_by(Course.create_time.desc()).all()
            data = marshal(course, course_fields)
            # if sort == 1:
            #     def myFunc(e):    # 排序的函数
            #         return e['create_time']
            #     data.sort(reverse=True,key=myFunc)  # 列表的排序 reverse=True代表降序 默认升序
            # else:
            #     def myFunc(e):    # 排序的函数
            #         return e['follower']
            #     data.sort(reverse=True,key=myFunc)  # 列表的排序 reverse=True代表降序 默认升序
            return jsonify(code=200, msg='课程获取成功', data=data)


        # 点击标签 和 状态
        if tag_id and free == '' and online and sort == '':
            tag = Tag.query.filter_by(id=tag_id).first()
            course1= tag.course
            course2 = Course.query.filter_by(status=online).all()
            data1 = marshal(course1, course_fields)
            data2 = marshal(course2, course_fields)
            data=[]
            for i in data2:
                if i in data1:
                    data.append(i)

            return jsonify(code=200, msg='课程获取成功', data=data)

        # 点击标签 和 排序
        if tag_id and free == '' and online == '' and sort:

            tag = Tag.query.filter_by(id=tag_id).first()
            course = tag.course
            data = marshal(course, course_fields)
            # if sort == 1:
            #     def myFunc(e):    # 排序的函数
            #         return e['create_time']
            #     data.sort(reverse=True,key=myFunc)  # 列表的排序 reverse=True代表降序 默认升序
            # else:
            #     def myFunc(e):    # 排序的函数
            #         return e['follower']
            #     data.sort(reverse=True,key=myFunc)  # 列表的排序 reverse=True代表降序 默认升序
            return jsonify(code=200, msg='课程获取成功', data=data)


        # 点击状态 和 排序
        if tag_id == '' and free == '' and online and sort:
            if sort == 1:
                course = Course.query.filter_by(status=online).order_by(Course.create_time.desc()).all()
                data = marshal(course, course_fields)
                return jsonify(code=200, msg='课程获取成功', data=data)
            else:
                course = Course.query.filter_by(status=online).order_by(Course.follower.desc()).all()
                data = marshal(course, course_fields)
                return jsonify(code=200, msg='课程获取成功', data=data)


        # 点击分类 和 标签 和 状态
        if tag_id and free and online and sort == '':
            free = CourseType.query.filter_by(title=free).first()
            course1 = Course.query.filter_by(course_type=free.id,status=online).all()
            tag = Tag.query.filter_by(id=tag_id).first()
            course2 = tag.course
            data1 = marshal(course1,course_fields)
            data2 = marshal(course2,course_fields)
            data=[]
            for i in data1:
                if i in data2:
                    data.append(i)
            return jsonify(code=200, msg='课程获取成功', data=data)

        # 点击分类 和 标签 和 排序
        if tag_id and free and online == '' and sort:
            free = CourseType.query.filter_by(title=free, status=online).first()
            course1 = free.course
            tag = Tag.query.filter_by(id=tag_id, status=online).first()
            course2 = tag.course
            data1 = marshal(course1, course_fields)
            data2 = marshal(course2, course_fields)
            data = []
            for i in data1:
                if i in data2:
                    data.append(i)
            # if sort == 1:
            #     def myFunc(e):    # 排序的函数
            #         return e['create_time']
            #     data.sort(reverse=True,key=myFunc)  # 列表的排序 reverse=True代表降序 默认升序
            # else:
            #     def myFunc(e):    # 排序的函数
            #         return e['follower']
            #     data.sort(reverse=True,key=myFunc)  # 列表的排序 reverse=True代表降序 默认升序
            return jsonify(code=200, msg='课程获取成功', data=data)

        # 点击标签 和 状态 和 排序
        if tag_id and free == '' and online and sort:
            tag = Tag.query.filter_by(id=tag_id).first()
            course1 = tag.course
            course2 = Course.query.filter_by(status=online).all()
            data1 = marshal(course1, course_fields)
            data2 = marshal(course2, course_fields)
            data = []
            for i in data2:
                if i in data1:
                    data.append(i)
            # if sort == 1:
            #     def myFunc(e):  # 排序的函数
            #         return e['create_time']
            #     data.sort(reverse=True, key=myFunc)  # 列表的排序 reverse=True代表降序 默认升序
            # else:
            #     def myFunc(e):  # 排序的函数
            #         return e['follower']
            #     data.sort(reverse=True, key=myFunc)  # 列表的排序 reverse=True代表降序 默认升序
            return jsonify(code=200, msg='课程获取成功', data=data)

        # 点击分类 和 状态 和 排序
        if tag_id == '' and free and online and sort:
            free = CourseType.query.filter_by(title=free).first()
            course = Course.query.filter(and_(Course.course_type == free.id, Course.status == online)).all()
            data = marshal(course, course_fields)
            # if sort == 1:
            #     def myFunc(e):  # 排序的函数
            #         return e['create_time']
            #     data.sort(reverse=True, key=myFunc)  # 列表的排序 reverse=True代表降序 默认升序
            # else:
            #     def myFunc(e):  # 排序的函数
            #         return e['follower']
            #     data.sort(reverse=True, key=myFunc)  # 列表的排序 reverse=True代表降序 默认升序
            return jsonify(code=200, msg='课程获取成功', data=data)
        # 点击所有
        if tag_id and free and online and sort:
            free = CourseType.query.filter_by(title=free).first()
            course1 = Course.query.filter_by(course_type=free.id,status=online).all()
            tag = Tag.query.filter_by(id=tag_id).first()
            course2 = tag.course
            data1 = marshal(course1, course_fields)
            data2 = marshal(course2, course_fields)
            data = []
            for i in data1:
                if i in data2:
                    data.append(i)
            # if sort == 1:
            #     def myFunc(e):  # 排序的函数
            #         return e['create_time']
            #     data.sort(reverse=True, key=myFunc)  # 列表的排序 reverse=True代表降序 默认升序
            # else:
            #     def myFunc(e):  # 排序的函数
            #         return e['follower']
            #     data.sort(reverse=True, key=myFunc)  # 列表的排序 reverse=True代表降序 默认升序
            return jsonify(code=200, msg='课程获取成功', data=data)
    # def get(self):
    #     """获取所有的课程"""
    #     parser = reqparse.RequestParser()
    #     params = ['page', 'size', 'tag_id', 'free', 'online', 'sort']
    #     for data in params:
    #         parser.add_argument(data)
    #     args = parser.parse_args()
    #     tag_id = args.get('tag_id')
    #     free = args.get('free')
    #     online = args.get('online')
    #     sort = args.get('sort')
    #     print("tag_id的值%s, online的值%s, free的值%s,sort的值%s" % (tag_id, online, free, sort))
    #
    #     # 2.若有的参数有值,有的参数没有值, 是根据参数值进行过滤查询
    #     if tag_id:
    #         print("标签有值", tag_id)
    #         tag = Tag.query.filter_by(id=int(tag_id)).first()
    #         course_data = None
    #         # 若标签有值
    #         # 获取标签
    #         if free == "" and online == '':
    #             course_tag = Tag.query.filter_by(id=int(tag_id)).first()
    #             # 获取所标签下的所有的值
    #             courses = course_tag.course
    #             course_data = marshal(courses, course_fields)
    #
    #         if free != '' and online == '':
    #             # free是免费的限免会员
    #             print("free", free)
    #             course_type = CourseType.query.filter_by(title=free).first()
    #             # 根据类型获取, 然后再根据tag_id 过滤
    #             course_data = marshal(course_type.course, course_fields)
    #
    #         if free != '' and online != '':
    #             course_type = CourseType.query.filter_by(title=free).first()
    #             if online == '1':
    #                 online_v = '已上线'
    #             else:
    #                 online_v = '即将上线'
    #             print(online_v, type(online))
    #             courses = Course.query.filter(
    #                 and_(Course.course_type == course_type.id, Course.status == online_v)).all()
    #             course_data = marshal(courses, course_fields)
    #         # 根据tag_id 过滤
    #         filter_course = json.loads(json.dumps(course_data))
    #         print("_____>", filter_course)
    #         for course in filter_course:
    #             if course['course_type'] != tag.id:
    #                 filter_course.remove(course)
    #         return filter_course
    #
    #     else:
    #         # 标签没有值
    #         # print(json.loads(json.dumps(course_list)))
    #         # 全部为空, 查询全部数据
    #         if sort == "" and tag_id == "" and online == "" and free == "":
    #             course_list = Course.query.all()
    #             course_data = marshal(course_list, course_fields)
    #             return jsonify(message='ok', code=200, data=course_data)
    #         if free != "" and online == '':
    #             course_type = CourseType.query.filter_by(title=free).first()
    #             course_data = marshal(course_type.course, course_fields)
    #             print("_____>", course_data)
    #             return course_data
    #         if online != '' and free == '':
    #             if online == '1':
    #                 online_v = '已上线'
    #             else:
    #                 online_v = '即将上线'
    #             courses = Course.query.filter_by(status=online_v).all()
    #             course_data = marshal(courses, course_fields)
    #             return course_data
    #         if online != '' and free != '':
    #             course_type = CourseType.query.filter_by(title=free).first()
    #             if online == '1':
    #                 online_v = '已上线'
    #             else:
    #                 online_v = '即将上线'
    #             courses = Course.query.filter(
    #                 and_(Course.course_type == course_type.id, Course.status == online_v)).all()
    #             course_data = marshal(courses, course_fields)
    #             return course_data

class Courseinfo(Resource):
    @login_auth
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('cid')
        args = parser.parse_args()
        cid = args['cid']
        course = Course.query.filter_by(id=cid).first()

        chapter_list = course.chapters
        course_data = {}
        chapter_data = []
        for chapter in chapter_list:
            course_data={
                    'id':chapter.id,
                    'title':course.title,
                    'serial_num':chapter.serial_num,
                    'course':chapter.course,
                    'collect_num':course.follower
                    # 'sections':chapter.sections
                }


            chapter_data.append({
                'id':chapter.id,
                'title':chapter.title,
                'sections':json.loads(json.dumps(marshal(chapter.sections,sections_fields)))
            })
        result = {
            'course_ser':course_data ,
            'section_ser':chapter_data
        }

        # chapters = json.loads(json.dumps(marshal(chapter_list,chapters_fields)))
        #         # course_data = {}
        #         # course_data['id'] = course.id
        #         # course_data['course_ser'] = chapters
        #         # for i in chapters:
        #         #     sec = Sections.query.filter_by(chapters = i['id']).all()
        #         #     sections = json.loads(json.dumps(marshal(sec,sections_fields)))
        #         #     i['section_ser'] = sections
        return jsonify(code=200,msg='获取成功',data = result)

class VideoInfo(Resource):
    @login_auth
    def get(self):
        parse = reqparse.RequestParser()
        parse.add_argument('sid')
        args = parse.parse_args()
        sid = args['sid']
        section = Sections.query.filter_by(id=sid).first()
        video_url = section.video
        return jsonify(code=200,url=video_url)




class CourseAdd(Resource):
    def post(self):
        parse = reqparse.RequestParser()
        parse.add_argument('title')
        parse.add_argument('desc')
        parse.add_argument('img_path')
        parse.add_argument('tag')
        parse.add_argument('course_type')
        parse.add_argument('status')
        parse.add_argument('follower')
        parse.add_argument('learner')
        args = parse.parse_args()
        title = args['title'] # 标题
        desc = args['desc']  # 详情
        img_path = args['img_path'] #封面
        tag = args['tag'] # 标签
        course_type = args['course_type'] # 类型
        status = args['status']  # 状态
        follower = args['follower'] # 关注人数
        learner = args['learner']  # 学习人数
        course = Course(title=title,desc=desc,img_path=img_path,course_type=course_type,status=status,follower=follower,learner=learner)
        db.session.add(course)
        db.session.commit()
        courses = Course.query.filter_by(title=title).first()
        course_tag = CourseTag(course_id=courses.id, tag_id=tag)
        db.session.add(course_tag)
        db.session.commit()
        return jsonify(code=200,msg='添加课程成功')













api.add_resource(TagsResource,'/get_tag')
api.add_resource(CourseAll,'/get_course')
api.add_resource(Courseinfo,'/courseinfo')
api.add_resource(VideoInfo,'/sectionvideo')
api.add_resource(CourseAdd,'/add_course')